package com.liusha.quicksand.service;

import com.liusha.quicksand.NotFoundException;
import com.liusha.quicksand.dao.TypeRepository;
import com.liusha.quicksand.po.Type;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 一世长安一世欢
 * @Date: 2020/10/28
 * @Time: 14:04
 * @Description: No Description
 */

@Service
public class  TypeServiceImpl implements TypeService {

    @Autowired
    private TypeRepository typeRepository;

    @Transactional
    @Override
    public Type saveType(Type type) {

        return typeRepository.save(type);
    }

    @Transactional
    @Override
    public Type getType(Long id) {

        return typeRepository.findById(id).get();
    }

    @Transactional
    @Override
    public Page<Type> listType(Pageable pageable) {

        return typeRepository.findAll(pageable);
    }

    @Transactional
    @Override
    public Type updateType(Long id, Type type) {

        Type t = typeRepository.findById(id).get();

        if (t == null) {
            throw new NotFoundException("不存在该分类！");
        }

        BeanUtils.copyProperties(type, t);

        return typeRepository.save(t);
    }

    @Transactional
    @Override
    public void deleteType(Long id) {

        typeRepository.deleteById(id);
    }

    @Override
    public Type getTypeByName(String name) {

        return typeRepository.findByName(name);
    }

    @Override
    public List<Type> listTypeTop(Integer size) {

        /*dddd*/
        Sort sort = Sort.by(Sort.Direction.DESC, "blogs.size");
        /*dddd*/

        Pageable pageable = PageRequest.of(0, size, sort);

        return typeRepository.findTop(pageable);
    }

    @Override
    public List<Type> listType() {

        return typeRepository.findAll();
    }
}
